import cv2 as cv

#使用基于混合高斯模型的背景提取算法，提取前景并显示(显示二值化图像，前景为白色)。
videoFileName = r'../video/vtest.avi'
cap = cv.VideoCapture(videoFileName)
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200
kernel =cv.getStructuringElement(cv.MORPH_ELLIPSE, (3,3))

while True:
    ret, frame = cap.read()
    if not ret:
        break
    fgmask = fgbg.apply(frame)
    _,fgmask = cv.threshold(fgmask,30,0xff,cv.THRESH_BINARY)
    bgImage = cv.morphologyEx(fgmask, cv.MORPH_OPEN ,kernel)

    _,cnts,_ = cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    count = 0
    for c in cnts:
        area = cv.contourArea(c)
        if(area < thresh):
            continue
        count += 1
        x,y,w,h = cv.boundingRect(c)
        cv.rectangle(frame,(x,y),(x+w,y+h), (0, 0xff, 0),2)
        print("pos:%d %d, size %d x %d" % (x,y,w,h))
    print("detect", count," targets")

    cv.imshow('frame', frame)
    cv.imshow('backgroud', bgImage)

    key = cv.waitKey(30)    #间隔30ms
    if key == 27: #esc
        break

cap.release()
cv.destroyAllWindows()
print('done!')




